<template>
    <el-upload
        ref="upload"
        v-bind="$attrs"
        :file-list="fileList"
        class="upload-box"
        action="/"
        :headers="{}"
        :multiple="multiple"
        :accept="accept"
        :limit="limit"
        :show-file-list="showFileList"
        :before-upload="beforeUpload"
        :on-preview="handlePreview"
        :on-remove="handleRemove"
        :before-remove="beforeRemove"
        :on-exceed="handleExceed"
    >
     <el-icon v-if="isImg"><Plus /></el-icon>
     <el-button v-else type="primary">上传</el-button>
  </el-upload>
  <el-dialog v-model="dialogVisible">
    <img w-full :src="dialogImageUrl" alt="Preview Image" />
  </el-dialog>
</template>

<script setup>
import { ref } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'

let emit = defineEmits(['removeFile', 'preview'])
const props = defineProps({
  fileList: {
    type: Array,
    default: () => []
  },
  accept: {
    type: String,
    default: '*'
  },
  multiple: {
    type: Boolean,
    default: false
  },
  showFileList: {
    type: Boolean,
    default: true
  },
  limit: {
    type: Number,
    default: 0
  },
  isImg: {
    type: Boolean,
    default: false
  }
})
const dialogImageUrl = ref('')
const dialogVisible = ref(false)

// const fileList = ref([
//   {
//     name: 'element-plus-logo.svg',
//     url: 'https://element-plus.org/images/element-plus-logo.svg',
//   },
//   {
//     name: 'element-plus-logo2.svg',
//     url: 'https://element-plus.org/images/element-plus-logo.svg',
//   },
// ])
const beforeUpload = (file) => {
  console.log('beforUpload',file)
    
  //   formDataToMD5(file, (md5Str) => {
  //     this.extraData.md5 = md5Str;
  //     // 获取md5后进行文件上传
  //     this.$refs.upload.post(file);
  //   });
  return true
}
const handleRemove = (file, uploadFiles) => {
  console.log('handleRemove',file, uploadFiles)
  emit('removeFile', file)
}

const handlePreview = (uploadFile) => {
  console.log('handlePreview',uploadFile)
  if(props.isImg) {
    dialogImageUrl.value = uploadFile.url
    dialogVisible.value = true
  } else {
    emit('preview', uploadFile)
  }

//   window.open(`${process.env.VUE_APP_REQUEST_BASE_URL}/document/attachment/inline/${file.id}?token=${this.$store.state.user.token}`)
}

// eslint-disable-next-line no-unused-vars
const handleExceed = (files, uploadFiles) => {
  ElMessage.warning('超出条数限制')
}

// eslint-disable-next-line no-unused-vars
const beforeRemove = (uploadFile, uploadFiles) => {
  return ElMessageBox.confirm('确认删除当前文件吗？').then(
    () => {
      console.log('确认删除')
      return true
    },
    () => {
      console.log('不删除')
      return false
    }
  )
}

</script>

<style lang="scss" scoped>
:deep(.el-upload-list__item .el-icon--close-tip) {
    opacity: 0;
}
</style>